package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.Utils.DateUtils;
import com.itheima.dao.OrderSettingDao;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.OrderSetting;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName OrderSettingServiceImpl
 * @Description: TODO
 * @Author 郑乾
 * @Date 2020-06-26
 * @Version V1.0
 **/
@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    OrderSettingDao orderSettingDao;

    @Transactional
    @Override
    public void addOrderSettingList(List<OrderSetting> orderSettingList) {
        //存储或者更新数据库
        if (orderSettingList != null && orderSettingList.size() > 0) {
            for (OrderSetting orderSetting : orderSettingList) {
                saveOrEdit(orderSetting);
            }
        }
    }

    @Override
    public List<OrderSetting> findByMonth(String date){
        String thisMonthFirstDay = date + "-01";
        Date thisMonthLastDay = DateUtils.getThisMonthLastDay(thisMonthFirstDay);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(thisMonthLastDay);
        return orderSettingDao.findByMonth(thisMonthFirstDay,format);
    }

    @Transactional
    public void saveOrEdit(OrderSetting orderSetting) {
        //根据日期查询是否已经存在预约
        OrderSetting orderSetting2 = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());
        if (orderSetting2 == null) {
            orderSettingDao.add(orderSetting);
        } else {
            if (orderSetting2.getReservations() > orderSetting.getNumber()) {
                throw new BusinessRuntimeException("已经预约人数不能大于可预约人数");
            } else {
                orderSettingDao.edit(orderSetting);
            }
        }
    }
}
